package cinescope2014.boundaries;

import cinescope2014.utilities.Globale;
import java.sql.*;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author pascal
 */
public class JIFGenreCRUD extends javax.swing.JInternalFrame {

    private Connection icn;
    private DefaultTableModel idtm;

    /**
     * Creates new form JIFGenreCRUD
     */
    public JIFGenreCRUD() {
        initComponents();

        setTitle("CRUD Genres");

        try {
            // --- Connexion
//            Class.forName("org.gjt.mm.mysql.Driver");
//            String lsDSN = "jdbc:mysql://127.0.0.1:3306/cinescope2014";
//            icn = DriverManager.getConnection(lsDSN, "root", "");
            icn = Globale.getConnexion();
            idtm = (DefaultTableModel) jTableGenres.getModel();

            String lsSQL;
            PreparedStatement lpst;
            ResultSet lrs;

            lsSQL = "SELECT * FROM genre ORDER BY code_genre";
            lsSQL = "{CALL genreSelectAll()}";
            lpst = icn.prepareStatement(lsSQL);
            lrs = lpst.executeQuery();

            Object[] tLigne;

            while (lrs.next()) {
                tLigne = new Object[4];

                tLigne[0] = lrs.getString(1);
                tLigne[1] = lrs.getString(2);
                tLigne[2] = lrs.getString(3);
                tLigne[3] = lrs.getString(4);

                idtm.addRow(tLigne);
            }

            lrs.close();
            lpst.close();

            jLabelMessage.setText("Okay !!!");

        } catch (SQLException ex) {
            jLabelMessage.setText(ex.getMessage());
        }

        setVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTableGenres = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabelMessage = new javax.swing.JLabel();
        jTextFieldCode = new javax.swing.JTextField();
        jTextFieldNom = new javax.swing.JTextField();
        jButtonAjouter = new javax.swing.JButton();
        jButtonSupprimer = new javax.swing.JButton();
        jButtonModifier = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jLabelID = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldGrammatical = new javax.swing.JTextField();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        jTableGenres.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Code", "Nom", "Grammatical"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, true, true, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableGenres.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTableGenresMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTableGenres);

        jLabel1.setText("Code");

        jLabel2.setText("Nom");

        jLabelMessage.setText("Message");

        jTextFieldCode.setText("TH");

        jTextFieldNom.setText("Thriller");

        jButtonAjouter.setText("Ajouter");
        jButtonAjouter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAjouterActionPerformed(evt);
            }
        });

        jButtonSupprimer.setText("Supprimer");
        jButtonSupprimer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSupprimerActionPerformed(evt);
            }
        });

        jButtonModifier.setText("Modifier");
        jButtonModifier.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonModifierActionPerformed(evt);
            }
        });

        jLabel5.setText("ID");

        jLabelID.setForeground(new java.awt.Color(255, 0, 51));
        jLabelID.setText("ID");

        jLabel3.setText("Grammatical");

        jTextFieldGrammatical.setText("M");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jScrollPane1)
                        .addComponent(jLabelMessage, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel1)
                                .addComponent(jLabel2)
                                .addComponent(jLabel5))
                            .addGap(54, 54, 54)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jTextFieldCode, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jTextFieldNom, javax.swing.GroupLayout.DEFAULT_SIZE, 182, Short.MAX_VALUE)
                                .addComponent(jLabelID, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jTextFieldGrammatical)))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jButtonAjouter)
                            .addGap(43, 43, 43)
                            .addComponent(jButtonModifier)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButtonSupprimer)))
                    .addComponent(jLabel3))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jLabelID))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jTextFieldCode, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldNom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextFieldGrammatical, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonAjouter)
                    .addComponent(jButtonModifier)
                    .addComponent(jButtonSupprimer))
                .addGap(18, 18, 18)
                .addComponent(jLabelMessage)
                .addGap(10, 10, 10))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
        // 

//        try {
//            icn.close();
//        } catch (SQLException e) {
//            System.err.println(e.getMessage());
//        }
    }//GEN-LAST:event_formInternalFrameClosing

    private void jButtonAjouterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAjouterActionPerformed
        /*
         Toutes les saisies obligatoires
         Code sur 2 caractères (Expression reguliere)
         Nom >= 2 caractères (Expression reguliere)
         Genre grammatical sur 1 caractère 'M' ou 'F'
         */
        StringBuilder lsbMessage = new StringBuilder();
        int liKO = 0;
        String lsCode = jTextFieldCode.getText();
        String lsNom = jTextFieldNom.getText();
        String lsGrammatical = jTextFieldGrammatical.getText();
        String lsModif;

        if (lsCode.equals("") || lsNom.equals("") || lsGrammatical.equals("")) {
            liKO++;
            jLabelMessage.setText("Toutes les saisies sont obligatoires !!!");
        }

        lsModif = "[A-Za-z]{2}";
        if (!lsCode.matches(lsModif)) {
            liKO++;
            lsbMessage.append("Code KO-");
        }
        lsModif = "[A-Za-z]{2,}";
        if (!lsNom.matches(lsModif)) {
            liKO++;
            lsbMessage.append("Nom KO-");
        }
        lsModif = "[F|M|f|m]";
        if (!lsGrammatical.matches(lsModif)) {
            liKO++;
            lsbMessage.append("Grammatical KO-");
        }

        if (liKO == 0) {
            try {
                String lsSQL;
                lsSQL = "INSERT INTO genre(id_genre, code_genre, libelle_genre, genre_grammatical) VALUES(?,?,?,?)";
                lsSQL = "{CALL genreInsert(?,?,?,?)}";
                PreparedStatement lpst = icn.prepareStatement(lsSQL);
                lpst.setInt(1, Types.NULL);
                lpst.setString(2, lsCode);
                lpst.setString(3, lsNom);
                lpst.setString(4, lsGrammatical);
                lpst.executeUpdate();
                icn.commit();
                lpst.close();
                // Rafraichissement de la JTable
                String[] tLigne = new String[4];
                tLigne[0] = "";
                tLigne[1] = lsCode;
                tLigne[2] = lsNom;
                tLigne[3] = lsGrammatical;
                idtm.addRow(tLigne);

                jLabelMessage.setText("Okay !!!");
            } catch (SQLException e) {
                jLabelMessage.setText(e.getMessage());
                System.err.println(e.getMessage());
            }
        } else {
            lsbMessage.deleteCharAt(lsbMessage.length() - 1);
            jLabelMessage.setText(lsbMessage.toString());
        }
    }//GEN-LAST:event_jButtonAjouterActionPerformed

    private void jButtonModifierActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonModifierActionPerformed
        // CF ajouter pour les controles
        if (jTableGenres.getSelectedRow() == -1) {
            jLabelMessage.setText("Sélectionnez une ligne !!!");
        } else {
            try {
                String lsSQL;
                //lsSQL = "UPDATE genre SET libelle_genre=? WHERE code_genre=?";
                // genreUpdate(paramID_GENRE INT(10),paramCODE_GENRE CHAR(2),paramLIBELLE_GENRE VARCHAR(50),paramGENRE_GRAMMATICAL CHAR(1))
                lsSQL = "CALL genreUpdate(?,?,?,?)";
                PreparedStatement lpst = icn.prepareStatement(lsSQL);
//                lpst.setString(1, jTextFieldNom.getText());
//                lpst.setString(2, jTextFieldCode.getText());
                lpst.setString(1, jLabelID.getText());
                lpst.setString(2, jTextFieldCode.getText());
                lpst.setString(3, jTextFieldNom.getText());
                lpst.setString(4, jTextFieldGrammatical.getText());
                lpst.executeUpdate();
                icn.commit();
                lpst.close();

                idtm.setValueAt(jTextFieldCode.getText(), jTableGenres.getSelectedRow(), 1);
                idtm.setValueAt(jTextFieldNom.getText(), jTableGenres.getSelectedRow(), 2);
                idtm.setValueAt(jTextFieldGrammatical.getText(), jTableGenres.getSelectedRow(), 3);

                jLabelMessage.setText("Okay !!!");
            } catch (SQLException e) {
                jLabelMessage.setText(e.getMessage());
                System.err.println(e.getMessage());
            }
        }
    }//GEN-LAST:event_jButtonModifierActionPerformed

    private void jButtonSupprimerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSupprimerActionPerformed
        // 
        int liLigneSelectionnee = jTableGenres.getSelectedRow();
        PreparedStatement lpst;
        ResultSet lrs;
        String lsSQL;

        if (liLigneSelectionnee == -1) {
            jLabelMessage.setText("Sélectionnez une ligne !!!");
        } else {
            try {
                if (jTableGenres.getValueAt(liLigneSelectionnee, 0).toString().equals("")) {
                    lsSQL = "SELECT id_genre FROM genre WHERE code_genre=?";
                    lpst = icn.prepareStatement(lsSQL);
                    lpst.setString(1, jTextFieldCode.getText());
                    lrs = lpst.executeQuery();
                    lrs.next();
                    //jTableGenres.setValueAt(lrs.getString(1), liLigneSelectionnee, 0);
                    jLabelID.setText(lrs.getString(1));
                    lrs.close();
                    lpst.close();
                }

                lsSQL = "DELETE FROM genre WHERE id_genre=?";
                lsSQL = "{CALL genreDelete(?)}";
                lpst = icn.prepareStatement(lsSQL);
                lpst.setString(1, jLabelID.getText());
                lpst.executeUpdate();
                icn.commit();
                lpst.close();

                idtm.removeRow(liLigneSelectionnee);

                jLabelMessage.setText("Okay !!!");

            } catch (SQLException e) {
                jLabelMessage.setText(e.getMessage());
                System.err.println(e.getMessage());
            }
        }
    }//GEN-LAST:event_jButtonSupprimerActionPerformed

    private void jTableGenresMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableGenresMouseClicked
        // 
        int liLigne = jTableGenres.getSelectedRow();

        jLabelID.setText(jTableGenres.getValueAt(liLigne, 0).toString());
        jTextFieldCode.setText(jTableGenres.getValueAt(liLigne, 1).toString());
        jTextFieldNom.setText(jTableGenres.getValueAt(liLigne, 2).toString());
        jTextFieldGrammatical.setText(jTableGenres.getValueAt(liLigne, 3).toString());
    }//GEN-LAST:event_jTableGenresMouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAjouter;
    private javax.swing.JButton jButtonModifier;
    private javax.swing.JButton jButtonSupprimer;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabelID;
    private javax.swing.JLabel jLabelMessage;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableGenres;
    private javax.swing.JTextField jTextFieldCode;
    private javax.swing.JTextField jTextFieldGrammatical;
    private javax.swing.JTextField jTextFieldNom;
    // End of variables declaration//GEN-END:variables
}
